package com.yangluyao.test.自旋;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author YLY
 * @ClassName SpinLockDemo  自定义自旋锁
 * @Date 2020/5/6
 * @Version 1.0.2
 */
public class SpinLockDemo {
    public static void main(String[] args) {
        SpinLockDemo spinLockDemo = new SpinLockDemo();
        new Thread(() -> {
            spinLockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLockDemo.myUnLock();
        }, "AA").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            spinLockDemo.myLock();
            spinLockDemo.myUnLock();
        }, "BB").start();
    }

    AtomicReference<Thread> atomicThread = new AtomicReference<>();

    public void myLock() {
        Thread thread =Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "\t come  in  myLock()");
        while (!atomicThread.compareAndSet(null, thread)){
        }
    }

    public void myUnLock() {
        Thread thread = Thread.currentThread();
        atomicThread.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t invoked  myLock()");
    }
}
